<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('头程装箱单-修改')" />
	<th:block th:include="include :: businessCSS" />
	<style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
		.preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}
		.tablebody{background-color: #fff;padding: 20px;margin-right: 15px;}
		.tablebody input{display: inline;width: 80%;border: none;}
		.tablebody table{width: 100%;}
		.tablebody th,.tablebody td{border:solid 1px #ddd;padding:10px;font-size:14px;text-align: center;}
	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
<!--        <div class="topbtns"><th:block th:include="include :: business_btn" /></div>-->
	    <div class="north" style="background-color: #fff;margin-top: 55px;">
			 <div class="layui-form-item preservationBtn">
                <button class="layui-btn layui-btn-normal dhicon btn-edit" type="button" lay-submit lay-filter="btn-edit" id="btn-edit">保存</button>
<!--                <button class="layui-btn layui-btn-normal dhicon btn-sh" type="button" lay-submit lay-filter="btn-sh" id="btn-sh">审核</button>-->
<!--                <button class="layui-btn layui-btn-normal dhicon btn-retreat" type="button" lay-submit lay-filter="btn-retreat" id="btn-retreat">回退</button>-->
			</div>
<!--			<div style="width: 100%;height: 65px;background: #f6f6f6;"></div>-->
			<div class="forminput"></div>
    	</div>
        <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
        <div>
            <table class="layui-hide" id="mjdhtable" lay-filter="mjtable"></table>
            <script type="text/html" id="zjtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">海外头程装箱清单</div>
            		<div>
<!--						<button class="layui-btn layui-btn-normal dhicon" th:classappend="${mjbtnSave} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${mjbtnSave} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">修改装箱清单</button>-->
						<button class="layui-btn layui-btn-normal dhicon updatebtn" classappend="'layui-btn-disabled'" lay-submit type="button"  lay-filter = "updatebtn" lay-event="updatebtn" id="updatebtn" th:if="${extraButton.updatebtn}">修改商品采购价</button>
						<button class="layui-btn layui-btn-normal dhicon astm" classappend="'layui-btn-disabled'" lay-submit type="button"  lay-filter = "astm" lay-event="astm" id="astm" >美标箱规</button>
            		</div>
            	</div>
            </script>
        </div>
        <th:block th:include="include :: pageFooter" />
    </form>
	</div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />
<script th:src="@{/dhecp/js/dh-toFixed.js}"></script>

<script th:inline="javascript">
	/*<![CDATA[*/
	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
	var mjbtnSave = [[${mjbtnSave}]];
	var List=[[${List}]];
	var listData1=List ?List:[]
	//箱重信息
	var boxWeight;
	//箱规长(cm)
	var boxLength;
	//箱规宽(cm)
	var boxHeigh1;
	//箱规高(cm)
	var boxWidth;
	//抛重(kg)
	var tossWeight;

	//A1(未跟单票起重判断的实际计重值)
	var a1 = 0;

	var weightCalBySingle;
	var singlePassCrane;
	//材质列表
	var textureList = [[${textureList}]];
	//仓库列表
	var logisticsMmodeCkList = [[${logisticsMmodeCkList}]];
	//材质名称
	var surchargeMaterialMax = $('#surchargeMaterialMax').val();
	//梯度
	var logisticsMmodeGrads = [[${logisticsMmodeGrads}]];
	//抛重梯度
	var logisticsMmodeInfoItems = [[${logisticsMmodeInfoItems}]];
	//品名梯度
	var wlpmtdList = [[${wlpmtdList}]];
	//材质最大值
	var texture = $('#priceQualityExtra').val();
	//表头数据
	var headData=[[${headData}]];
	//品名数量
	var gradeNum = new Set();
	let tablecolsNum = headData.numBox;
	let warehouseCost = 0;
	var tablecols=[ [
		{align: 'center',field: 'serial', title: '操作', width: 100 ,fixed: 'left'}
		,{align: 'center',field: 'vDFilesDefault', title: '透明标附件', width: 100,fixed: 'left'}
		,{align: 'center',field: 'isSign', title: '透明标记', width: 100,fixed: 'left'}
		,{align: 'center',field: 'signCode', title: '透明标记编码', width: 100,fixed: 'left'}
		,{align: 'center',field: 'commodityCode', title: '商品编码', width: 100,fixed: 'left'}
        ,{align: 'center',field: 'name', title: '商品名称', width: 250,fixed: 'left'}
		,{align: 'center',field: 'nameGoodsCn', title: '商品品名(中文)', width: 100}
		,{align: 'center',field: 'codeGoodsHs', title: '海关编码', width: 100}
		,{align: 'center',field: 'nameMaterialCn', title: '商品材质(中文)', width: 100}
        ,{align: 'center',field: 'priceIn', title: '商品采购价（¥）', width: 100}
        ,{align: 'center',field: 'linkJP', title: '竞品链接', width: 100}
        ,{align: 'center',field: 'vDFilesDefault', title: '是否有附件', width: 100,hide: true}
        ,{align: 'center',field: 'spGuid', title: '商品id', width: 100,hide: true}
		,{align: 'center',field: 'sku', title: 'SKU', width: 110}
		,{align: 'center',field: 'asin', title: 'ASIN', width: 110}
        ,{align: 'center',field: 'fnsku', title: 'FNSKU', width: 110}
        ,{align: 'center',field: 'numPlanDeliver', title: '计划发货数量', width: 100}
		,{align: 'center',field: 'numRealityDeliver', title: '实际发货数量', width: 100}
    ]]

	//根据coleSize编辑出多少个箱子
	for (let i = 0; i < tablecolsNum; i++) {
		let  tableData = {
			"align": "center",
			"field": "numRealityDeliver"+(i+1),
			"title": "箱子"+(i+1),
			"width": 95,
			// "edit": 'text',
		}
		tablecols[0].push(tableData);
	}

	//将箱子数据赋值
	if (tablecolsNum != 0){
		for (let i = 0; i < listData1.length; i++) {
			let ss = listData1[i].boxList.slice(1,listData1[i].boxList.length-1)
			let aa =  ss.split(",");
			for (let j = 0; j < aa.length; j++) {
				let numRe = 'numRealityDeliver'+(j+1)
				listData1[i][numRe] = aa[j]==0?"":$.trim(aa[j])
			}
		}
	}




	var $,layer,form,table,nid,noTable;
    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        beforeInit();//表单初始化之前的动作集合
		//初始化操作
		headcom3()
        nid=$('#nid').val()
         // 保存按钮事件变化
        $(function(){
           $('.tp-save').attr('onclick','')
           $('.tp-save').attr('lay-filter','btn-edit')
           $('.tp-save').attr('lay-submit',true)
        })

		//移除表格编辑属性  不等于制单中的时候禁用 已装箱和审核不能修改
		if (headData['state'] == 2 || headData['state'] == 1 || headData['state'] == 3){
			$.each(tablecols[0],function(i,v){
						delete v['edit']
					}
			)
		}

		//下拉框事件
		form.on('select(select_top)', function(data){
			calculateBoxDataNew();
		});

        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
			if ($('#numBox').val() <= 0){
				layer.msg("头程箱数不允许小于0");
				is_return=true;
			}
			if (Number($('#numProName').val()) > Number($('#numMaxProName').val())){
				layer.msg("实际品名数大于品名上限数,不允许下单!");
				is_return=true;
			}
			listData1.map((n,m)=>{
				if(is_return){
					return;
				}
				if(n.sku != null) {
					var tolNum = 0;
					for (let i = 1; i <= tablecolsNum; i++) {
						let numRe = 'numRealityDeliver'+i
                        if (n[numRe] != undefined && n[numRe] != ''){
							tolNum = tolNum + Number(n[numRe]);
						}
					}
					if (tolNum <= 0){
						// 实际发货数量不能为0
						layer.msg('SKU:'+n.sku+',实际发货数量不能为0');
						is_return=true;
						return
					}
				} else {
					//判断每条数据是否完善：比如箱重的信息未完善
					var numBox = $('#numBox').val();
					for (let i = 1; i <= numBox; i++) {
						let numRe = 'numRealityDeliver'+i
						if (n[numRe] == undefined || n[numRe] == ''){
							layer.msg(n.serial+'数据不全,请核实后再操作!');
							is_return=true;
							return
						}
					}
				}
			})
            if(is_return) return;
			postUrl(data)
			// isSinglePassCrane(data);
        });

		//按钮表格操作
		table.on('toolbar(mjtable)', function (obj) {
			switch (obj.event) {
				case 'astm':
					$.ajax({
						url: '/logstics/fbabox/astm',
						type: 'post',
						data: {infoMap:JSON.stringify(headData),infoItems:JSON.stringify(listData1)},
						dataType: 'html',
						success: function (result) {
							layer.open({
								type: 1,
								area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
								fix: false,//不固定
								offset: '10%',//距离顶部
								maxmin: true,//最大最小化
								shade: 0.3,//遮罩
								title: '美标箱规',
								content:result,
								btn: ['确定', '取消'],
								shadeClose: true,// 弹层外区域关闭
							});
						}
					});
					break;
				case 'mjbtn_save':
					$.modal.confirmCom('确定要修改装箱清单么？', function (result) {
						showloadings(true);
						calculateBoxDataNew();
						layer.msg('修改成功') ;
						setTimeout(function () {
							layer.closeAll();
							showloadings(false);
							table.reload('mjdhtable', {data:listData1});
						}, 1000);
					});
					break;
				case 'updatebtn':
					var str = `<div class="tablebody"><table class="layui-table zjtable"><thead><tr><th>商品编码</th><th>商品名称</th><th>商品采购价(¥)</th><th>竞品链接</th></tr></thead><tbody id="tbody">`;
					$.each(listData1, function (i, v) {
						if (v.commodityCode != null){
							str += `<tr>`;
							str += `<td>${v.commodityCode}</td>`;
							str += `<td>${v.nameGoodsCn}</td>`;
							str += `<td><input style="text-align: center"  type="test" onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, '$1')" name='priceIn' class='priceIn'  id='priceIn' value=${v.priceIn}></td>`;
							str += `<td style="display: none">${v.serial}</td>`;
							str += `<td><input style="text-align: center;"  type="test"  name='linkJP' class='linkJP'  id='linkJP' value=${v.linkJP}></td>`;
							str += `</tr>`;
						}
					});
					str += `</tbody></table></div>`;
					layer.open({
						type: 1,
						area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
						fix: false,//不固定
						offset: '10%',//距离顶部
						maxmin: true,//最大最小化
						shade: 0.3,//遮罩
						title: '修改商品采购价',
						content:str,
						btn: ['确定', '取消'],
						shadeClose: true,// 弹层外区域关闭
						yes: function(index, layero){
							showloadings(true);
							//获取修改后的清单信息
							var isjx=true
							var isLinP=true
							var trlist =$("#tbody").children("tr");
							var daraArr=[]
							//装箱是否有箱子数量
							var numRealityDeliverFList = new Map();
							//所有箱子下每个箱子的采购价格
							var numRealityDeliverPriceList = new Map();
							for (let i = 0; i <= tablecolsNum; i++) {
								numRealityDeliverFList.set("numRealityDeliver"+i, false);
								numRealityDeliverPriceList.set("numRealityDeliver"+i, 0);
							}
							for (var i = 0; i < trlist.length; i++) {
								let obj={}
								var tdarr = trlist.eq(i).find("td");
								obj.commodityCode = tdarr.eq(0).text();
								obj.nameGoodsCn = tdarr.eq(1).text();
								obj.priceIn = tdarr.eq(2).find("input").val();
								obj.priceIn = Number(obj.priceIn);
								obj.serial = tdarr.eq(3).text();
								obj.linkJP = tdarr.eq(4).find("input").val();
								if(obj.priceIn == null || obj.priceIn == '' || Number(obj.priceIn) == 0 || obj.priceIn == undefined)isjx=false
								if(obj.linkJP == null || obj.linkJP.trim() == '')isLinP=false
								daraArr.push(obj)
							}
							if(!isjx){
								showloadings(false) ;
								return layer.msg('请填写商品采购价') ;
							}
							if(!isLinP){
								showloadings(false) ;
								return layer.msg('请填写竞品链接') ;
							}

							//判断修改后的数据进行筛选在回填
							listData1.map((n,m)=>{
								if (!isNaN(n.serial)) {
									for (let j = 0; j < daraArr.length; j++) {
										if (n.serial == daraArr[j].serial){
											n.priceIn= daraArr[j].priceIn
											n.linkJP= daraArr[j].linkJP
										}
									}
									//判断是否有数量，用于单箱采购总价是否需要设置空值
									for (let i = 0; i <= tablecolsNum; i++) {
										let numRe = 'numRealityDeliver'+i
                                        if (n[numRe] != undefined && n[numRe] != ''){
											if (n[numRe] > 0){
												numRealityDeliverFList.set(numRe, true);
											}
										}
									}
									//累加单箱采购价
									for (let i = 0; i <= tablecolsNum; i++) {
										let numRe = 'numRealityDeliver'+i
                                        if (n[numRe] != undefined && n[numRe] != ''){
											numRealityDeliverPriceList.set(numRe, numRealityDeliverPriceList.get(numRe)+(n.priceIn * Number(n[numRe])));
										}
									}
								}
								if (n.serial == "单箱采购总价(￥)") {
									for (let i = 0; i <= tablecolsNum; i++) {
										let numRe = 'numRealityDeliver'+i
										//判断是否为空值，则取所有的采购价累加值
										n[numRe] = numRealityDeliverFList.get(numRe)? toFixed(numRealityDeliverPriceList.get(numRe),2):'';
									}
								}
							});
							layer.msg('修改成功') ;
							setTimeout(function () {
								layer.closeAll();
								sessionStorage.setItem(moduleTable + 'checkdata', '')
								showloadings(false);
								table.reload('mjdhtable', {data:listData1});
							}, 1000);
						}
					});
					break;
			};
		});


        
		// 初始化表格
        $.tablelist.init({
            elem: '#mjdhtable'
            ,data: listData1
            , page: false
            , even: true
            , limit: 10000
            , totalRow: false
            , cols: tablecols
            , toolbar: '#zjtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '550'
            , done: function (res, curr, count) {
                listData1 = table.cache.mjdhtable;//每次重载都赋值更新表缓存
				if (headData['state'] == 1){
					$('.btn-sh').attr('disabled',true)
					$('.btn-sh').css('background',"#bbb")
					$('.btn-edit').attr('disabled',true)
					$('.btn-edit').css('background',"#bbb")
					$('.layui-col-xs4').attr("disabled",true);
					$('input').attr('disabled','disabled')
					$('input').addClass('canntEdit')
					$('.forminput').addClass('layui-disabled')
					$('.updatebtn').css('background',"#bbb")
					$('.updatebtn').attr('disabled',true)
				}
				// $('th').css({ 'background-color': '#BCD2EE', 'color': 'black' });//设置th颜色
				//更新装箱清单样式
				var that = this.elem.next();
				res.data.forEach(function (item, index) {
					 if (item.scrapData == "1" && item.serial != "合计") {
						 var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", '#e5f3fe');
					 } else {
						var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", 'white');
					 }
			    })
            },success:function(a,b,c){
                console.log(a,b,c)
            }
        });

        //监听单元格编辑
        table.on('edit(mjtable)', function(obj) {
			var tr = obj.tr;
			var regular = /^[+]{0,1}(\d+)$/  //正数 （不包括小数）
			var regular2 = /^[0-9]+(.[0-9]{0,2})?$/
			// 单元格编辑之前的值
			var oldtext = $(tr).find("td[data-field='"+obj.field+"'] div").text();
			let fxa = true;
			//判断是否数值匹配
			listData1.map((n,m)=>{
				if(n.commodityCode == obj.data.commodityCode && n.commodityCode != null){
					if(n.sku != null){
						if (!regular.test(obj.value) && obj.value != '') {
							n[obj.field]  = oldtext;
							layer.msg("箱子数量只允许输入正整数,请核实后在操作!")
							fxa = false;
							return
						}
						if (obj.value == "0"){
							//当0设置空值
							n[obj.field] = '';
							layer.msg("箱数不允许填入0,请核实后在操作!")
							fxa = false;
						}
						var tolNum = 0;
						//累加所有箱子数量
						for (let i = 0; i <= tablecolsNum; i++) {
							let numRe = 'numRealityDeliver'+i
                            if (n[numRe] != undefined && n[numRe] != ''){
								tolNum = tolNum + Number(n[numRe]);
							}
						}

						if (n.numPlanDeliver < tolNum){
							//总的箱数不允许超过计划发货数量
							n[obj.field]  = oldtext;
							layer.msg('总的箱数不允许超过计划发货数量');
							fxa = false;
							return
						}
					}
				} else if(n.serial == obj.data.serial) {
					//箱规信息
					if (!regular2.test(obj.value) && obj.value != '') {
						n[obj.field]  = oldtext;
						layer.msg("箱规信息只允许输入两位小数点的正数,请核实后在操作!")
						fxa = false;
						return
					}
					if (obj.value == "0"){
						layer.msg("箱重信息不允许填入0,请核实后在操作!")
						//当0设置空值
						n[obj.field] = '';
						fxa = false;
					}
				}
			})
			if (!fxa){
				table.reload('mjdhtable', {data:listData1});
			}
		})

    });

	//根据数字未满5满5,未满10满10
	function precision(f) {
		var s = f.toString();
		var rs = s.indexOf('.');
		if (rs != -1) {
			//取出第一位
			var first = s.substring(0,rs);
			//根据第一位小数5来判断，大于0.5以上进1,小于0.5的为0.5
			first = first + '.5';
			if (f < first){
				f = first
			} else if(f > first) {
				f =Math.round(f);
			}
		}
		return f
	}

	/**
	 * 回调弹框事件
	 */
	function getMoreAfter(fieldsList,fields,tindex,fieldName,fieldSearchType,isSearch,isLayer,res) {//弹出框赋值回调
		if(fields=='nameLogsticsWay'){
			//根据物流方式guid获取详情信息
			$.get('/logstics/logisticsmmode/details',{guid:res.guid},function(ress){
				if(ress != null){
					textureList = ress.logisticsMmodeDetailsList;
					logisticsMmodeGrads = ress.logisticsMmodeGrads;
					logisticsMmodeInfoItems = ress.logisticsMmodeInfoItems;
					logisticsMmodeCkList = ress.logisticsMmodeCkList;
				}else{
					textureList = [];
				}
				calculateBoxDataNew();
				setTimeout(function () {
					sessionStorage.setItem(moduleTable + 'checkdata', '')
					table.reload('mjdhtable', {data:listData1});
				}, 1000);
			})
		}

	}





	/**
	 * 计算箱子数据
	 */
	function calculateBoxDataNew() {
		var weightReal = 0;
		var numBox = 0;
		//装箱是否有箱子数量
		var numRealityDeliverFList = new Map();
		//所有箱子下每个箱子的采购价格
		var numRealityDeliverPriceList = new Map();
		//合计的数量
		var numTolList = new Map();
		for (let i = 0; i <= tablecolsNum; i++) {
			numRealityDeliverFList.set("numRealityDeliver"+i, false);
			numRealityDeliverPriceList.set("numRealityDeliver"+i, 0);
			numTolList.set("numRealityDeliver"+i, 0);
		}
		numTolList.set("numRealityDeliver", 0);
		var weightVol = 0;
		texture = 0;
		surchargeMaterialMax= '';
		gradeNum.clear();
		listData1.map((n,m)=>{
			if (n.serial == "箱重(kg)") {
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
                    if (n[numRe] != undefined && n[numRe] != ''){
						weightReal = weightReal + Number(n[numRe]);
						numBox += 1;
					}
				}
				boxWeight = n;
			}
			if (n.serial == "箱规长(cm)") {
				boxLength = n;
			}
			if (n.serial == "箱规宽(cm)") {
				boxWidth = n;
			}
			if (n.serial == "箱规高(cm)") {
				boxHeigh1 = n;
			}
			if (n.serial == "抛重(kg)") {
				tossWeight = n;
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
					//每一箱箱规长的值
					let boxLengthVal = boxLength[numRe] != undefined?boxLength[numRe] : 0;
					//每一箱箱规宽的值
					let boxWidthVal = boxWidth[numRe] != undefined?boxWidth[numRe] : 0;
					//每一箱箱规高的值
					let boxHeigh1Val = boxHeigh1[numRe] != undefined?boxHeigh1[numRe] : 0;
					//判断是否有值,给空值
					if(boxLengthVal == 0 && boxWidthVal == 0 && boxHeigh1Val == 0){
						n[numRe] = '';
					}else {
						//抛重=（长*款*高）/抛重系数
						n[numRe] = toFixed(((boxLengthVal * boxWidthVal * boxHeigh1Val) / $('#coefficientWeight').val()),2)
					}
				}
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
                    if (n[numRe] != undefined && n[numRe] != ''){
						weightVol = weightVol + Number(n[numRe]);
					}
				}
			}
			if (!isNaN(n.serial)) {
				//不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
				var join = n.nameGoodsCn + '-' + n.codeGoodsHs + '-' +n.nameMaterialCn;
				gradeNum.add(join);
				//判断是否有数量，用于单箱采购总价是否需要设置空值
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
                    if (n[numRe] != undefined && n[numRe] != ''){
						if (n[numRe] > 0){
							numRealityDeliverFList.set(numRe, true);
						}
					}
				}
				//实际发货数量总和
				let numRealityDeliver = '';
				//累加单箱采购价和单箱合计
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
                    if (n[numRe] != undefined && n[numRe] != ''){
						numRealityDeliverPriceList.set(numRe, numRealityDeliverPriceList.get(numRe)+(n.priceIn * Number(n[numRe])));
						numRealityDeliver = Number(numRealityDeliver)+ Number(n[numRe]);
						numTolList.set(numRe, numTolList.get(numRe)+(Number(n[numRe])));
					}
				}
				n.numRealityDeliver = numRealityDeliver;
				numTolList.set('numRealityDeliver', numTolList.get('numRealityDeliver')+(Number(n.numRealityDeliver)));
			}
			if (n.serial == "单箱采购总价(￥)") {
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
					//判断是否为空值，则取所有的采购价累加值
					n[numRe] = numRealityDeliverFList.get(numRe)? toFixed(numRealityDeliverPriceList.get(numRe),2):'';
				}
			}
			if (n.serial == "合计") {
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
					//判断是否为空值，则取所有的箱子数量累加值
					n[numRe] = numTolList.get(numRe)? numTolList.get(numRe):'';
				}
				n.numRealityDeliver = numTolList.get('numRealityDeliver')? numTolList.get('numRealityDeliver'):'';
			}

			//判断是否是混合材质
			if (n.nameMaterialCn != null && typeof n.nameMaterialCn != "undefined") {
				if (n.nameMaterialCn.indexOf(",") == -1) {
					//赋值材质附加费(取最大值)
					for (let j = 0; j < textureList.length; j++) {
						if (textureList[j].materialName == n.nameMaterialCn) {
							if (textureList[j].materialCost > texture) {
								texture = textureList[j].materialCost;
								surchargeMaterialMax = textureList[j].materialName;
							}
						}
					}
				} else {
					var nameMaterialCnList = n.nameMaterialCn.split(",");
					nameMaterialCnList.forEach(item => {
						for (let j = 0; j < textureList.length; j++) {
							if (textureList[j].materialName == item) {
								if (textureList[j].materialCost > texture) {
									texture = textureList[j].materialCost
									surchargeMaterialMax = textureList[j].materialName;
								}
							}
						}
					});
				}
			}
		})

		//实际计重
		let weightCal= 0;
		//实际计重约分
		let weightCalNew= 0;
		//梯度计重单价
		let tdjzPrice;
		//实际计重单价
		let weightPrice;
		//抛货系数
		let predVal;
		//抛重梯度计重单价
		let phjzPrice;
		let phweightPrice;
		let weightVolPredictNew = 0;
		let priceClearanceOpePrice=100;
		let tradeNamePro;
		//单箱起重
		weightCalBySingle = $('#weightCalBySingle').val();
		//单票起重
		singlePassCrane = $('#singlePassCrane').val();

		//抛货计重=MAX（单箱抛重，单箱起重）之和（约分）
		for (let i = 0; i <= tablecolsNum; i++) {
			let numRe = 'numRealityDeliver'+i
			if (tossWeight[numRe] != undefined && tossWeight[numRe] != ''){
				weightVolPredictNew = weightVolPredictNew +Math.max(weightCalBySingle,(tossWeight[numRe]))
			}
		}
		weightVolPredictNew = precision(weightVolPredictNew);
		if ($('#stateShareTicketName').val() == '是') {
			if ($('#logisticsType').val() == '快递'){
				//当物流类型为快递时，不管拼票是或者否，实际计重=【MAX（单箱装箱实重，单箱装箱抛重，单箱起重）先进行约分，然后在所有箱子加起来】。
				weightCal = calculateWeightCal(weightCal,1);
				weightCalNew = weightCal;
			}else {
				//实际计重=MAX（实重,单箱起重）
				for (let i = 0; i <= tablecolsNum; i++) {
					let numRe = 'numRealityDeliver'+i
                    if (boxWeight[numRe] != undefined && boxWeight[numRe] != ''){
						weightCal = weightCal +Math.max(weightCalBySingle,(boxWeight[numRe]))
					}
				}
				weightCalNew = precision(weightCal);
			}


			//梯度计重单价=(实际计重满足区间的值)
			tdjzPrice = logisticsMmodeGrads.filter(items => weightCalNew >= items.startSection && weightCalNew <= items.endSection);
			//抛货系数=(抛重的值-实际计重)
			predVal = toFixed((weightVol - weightCalNew),2);
			//抛货计重单价=(抛货系数满足区间的值)
			pzjzPrice = logisticsMmodeInfoItems.filter(items => predVal >= items.startSection && predVal <= items.endSection);
			//计重单价=梯度计重单价+抛重计重单价
			weightPrice = (tdjzPrice[0]?tdjzPrice[0].kg:0) + (pzjzPrice[0]?pzjzPrice[0].kg:0);

			phweightPrice = (tdjzPrice[0]?tdjzPrice[0].kg:0);

			//抛重>实重，实际计重费=MIN(实际计重*计重单价,抛货计重费)；抛重<实重，实际计重费=实际计重*计重单价；
			let priceTranCalWeightPredict = toFixed((weightCalNew * weightPrice),2);
			if (weightVol > weightReal){
				if (parseFloat(priceTranCalWeightPredict)>=parseFloat(weightVolPredictNew* phweightPrice)){
					$('#priceTranCalWeightPredict').val(weightVolPredictNew* phweightPrice)
				}else {
					$('#priceTranCalWeightPredict').val(priceTranCalWeightPredict)
				}
			} else {
				$('#priceTranCalWeightPredict').val(priceTranCalWeightPredict)
			}

			//1.实际计重<单票起重的二分之一,实际品名数=免费品名数/2&向下取整
			let numWeightCal = weightCalNew<$('#singlePassCrane').val()/2;
			//实际品名数
			let numProName = gradeNum.size;
			//实际品名免费数
			let numFreeProName;
			if (numWeightCal){
				numFreeProName = $('#numFreeProNameNew').val()== 0?0: Math.floor($('#numFreeProNameNew').val()/2)
			}
			//2.实际计重>=单票起重的二分之一,实际品名数=免费品名数/2&向上取整
			if (!numWeightCal && weightCalNew<$('#singlePassCrane').val()){
				numFreeProName = $('#numFreeProNameNew').val()== 0?0: Math.ceil($('#numFreeProNameNew').val()/2)
			}
			if (Number(weightCalNew)>=Number($('#singlePassCrane').val())){
				//3.实际计重>=单票起重,实际品名数=免费品名数
				numFreeProName = $('#numFreeProNameNew').val()
				// numProName = numFreeProName
			}
			//超出品名=实际品名-实际免费品名数
			var num = numProName-numFreeProName;
			//品名免费数
			$('#numFreeProName').val(numFreeProName)
			$('#numProName').val(numProName);

			//清关费=清关费*清关占比
			if ($('#numMaxProName').val() != 0){
				tradeNamePro = toFixed(((gradeNum.size/$('#numMaxProName').val())*100),2)
				wlpmtdList.map((j,k)=>{
					if (tradeNamePro >= j.startSection && tradeNamePro<= j.endSection){
						priceClearanceOpePrice = j.kg
					}
				})
			}

			//预估清光费(物流方式清光费*品名占比)
			$('#priceClearanceOpe').val(toFixed(($('#priceClearanceOpeCs').val() * priceClearanceOpePrice/100),2));
		}else {
			if ($('#logisticsType').val() == '快递'){
				//当物流类型为快递时，不管拼票是或者否，实际计重=【MAX（单箱装箱实重，单箱装箱抛重，单箱起重）先进行约分，然后在所有箱子加起来】。
				weightCal = calculateWeightCal(weightCal,1);
				weightCalNew = weightCal;
			}else {
				//实际计重=【MAX（单箱装箱实重，单箱装箱抛重，单箱起重）先把所有箱子加起来，在进行约分向上取整】。实际计重=MAX（A1，单票起重）
				weightCal = calculateWeightCal(weightCal,2);
				weightCalNew = Math.ceil(weightCal);
				a1 = weightCalNew;
				//A1
				$('#weightCalA1').val(a1);
				weightCalNew = Math.max(singlePassCrane, weightCalNew);
			}
			//梯度计重单价=(实际计重满足区间的值)
			tdjzPrice = logisticsMmodeGrads.filter(items => weightCalNew >= items.startSection && weightCalNew <= items.endSection);
			//抛货系数=(抛重的值-实际计重)
			predVal = toFixed((weightVol - weightCalNew),2);
			//抛货计重单价=(抛货系数满足区间的值)
			pzjzPrice = logisticsMmodeInfoItems.filter(items => predVal >= items.startSection && predVal <= items.endSection);
			//计重单价=梯度计重单价+抛重计重单价
			weightPrice = (tdjzPrice[0]?tdjzPrice[0].kg:0);

			phweightPrice = weightPrice;
			//实际计重费=(预估计重*计重单价)
			$('#priceTranCalWeightPredict').val(toFixed((weightCalNew * weightPrice),2));
			//超出品名=实际品名-免费品名数
			var num = gradeNum.size-$('#numFreeProNameNew').val();
			//实际清光费
			$('#priceClearanceOpePrice').val($('#priceClearanceOpe').val())
			$('#numProName').val(gradeNum.size);

		}

		//获取当前的仓库附加单价
		warehouseCost = 0;
		for (let k = 0; k < logisticsMmodeCkList.length; k++) {
			if (logisticsMmodeCkList[k].warehouseName == $('#destinationFulfillmentCenterId').val()) {
				warehouseCost = logisticsMmodeCkList[k].warehouseCost;
			}
		}
		$('#warehouseSurchargePrice').val(warehouseCost)
		//仓库附加计重费用 = 仓库附件计重单价*实际计重
		$('#warehouseSurcharge').val(toFixed((weightCalNew * $('#warehouseSurchargePrice').val()),2));
		$('#priceTranCalWeightPredict').val(parseFloat($('#warehouseSurcharge').val()) + parseFloat($('#priceTranCalWeightPredict').val()));

		//实际实重
		$('#weightReal').val(toFixed(weightReal,2));
		//实际抛重
		$('#weightVol').val(toFixed(weightVol,2));
		//装箱计重
		$('#weightCal').val(weightCalNew);
		//头程箱数
		$('#numBox').val(numBox);
		//抛货系数
		$('#jettisonCoe').val(predVal);
		//梯度计重单价
		$('#tdjzPrice').val(tdjzPrice[0]?tdjzPrice[0].kg:0);
		//抛货计重单价
		$('#pzjzPrice').val(pzjzPrice[0]?pzjzPrice[0].kg:0);
		//计重单价
		$('#jzPrice').val(weightPrice);
		//抛货计重费
		$('#jettisonWeightCharge').val(toFixed((weightVolPredictNew* phweightPrice),2))
		//设置表头附加费材质
		$('#priceQualityExtra').val(texture);
		//最大附加费材质
		$('#surchargeMaterialMax').val(surchargeMaterialMax);
		//设置实际材质附加费=材质计费*实际计重
		$('#priceQualityExtraPredict').val(toFixed((texture*$('#weightCal').val()),2));
		//品名
		$('#numProNameBeyond').val(num>0?num:0);
		//占比
		$('#tradeNamePro').val(priceClearanceOpePrice)
		//预估品名附加费 = 超出的品名*品名标准
		$('#priceProNameExtraPredict').val(toFixed(($('#nameSurchargePrice').val() * $('#numProNameBeyond').val()),2));
		//实际物流费用 = 实际计重运费+实际材质附加费+实际品名附加费+实际清关费
		$('#actualLogisticsFreight').val(parseFloat($('#priceTranCalWeightPredict').val())+parseFloat($('#priceQualityExtraPredict').val())+parseFloat($('#priceProNameExtraPredict').val())+parseFloat($('#priceClearanceOpe').val()));
		//判断是否是抛重发货 -- 进行逻辑计算
		if ($('#loadDelivery').val() == 1){
			//实际抛发清关费=清关费单价
			$('#priceClearanceOpePf').val($('#priceClearanceOpeCs').val());
			//抛发实际品名免费数=品名免费数
			$('#numFreeProNamePf').val($('#numFreeProNameNew').val());
			//抛发超品名数量【=实际品名数-抛发实际品名免费数】
			var numPf = $('#numProName').val() - $('#numFreeProNamePf').val();
			numPf = numPf>0?numPf:0;
			//实际抛发品名附加费、费用说明：实际抛发品名附加费=超品名数量*品名附加费单价
			$('#priceProNameExtraPredictPf').val(toFixed((numPf * $('#nameSurchargePrice').val()),2));
			//抛发计重：【=MAX（装箱抛重，单票起重）约分】
			let  weightCalPf = precision(Math.max(weightVol, $('#singlePassCrane').val()))
			//实际抛发材质附加费、费用说明：实际抛发材质附加费=MAX（装箱抛重，单票起重）*材质附加单价
			$('#priceQualityExtraPredictPf').val(toFixed((weightCalPf * $('#priceQualityExtra').val()),2))
			//梯度计重单价=(实际计重满足区间的值)
			let pfLogisticsMmodeGrads = logisticsMmodeGrads.filter(items => weightCalPf >= items.startSection && weightCalPf <= items.endSection);
			pfjzPrice = (pfLogisticsMmodeGrads[0]?pfLogisticsMmodeGrads[0].kg:0);
			//抛发仓库费用
			$('#warehouseSurchargePf').val(toFixed((weightCalPf * $('#warehouseSurchargePrice').val()),2))
			//实际抛发计重运费、费用说明：实际抛发计重运费=MAX（装箱抛重，单票起重）*抛发计重单价+仓库附加计重费用
			$('#priceTranCalWeightPredictPf').val(toFixed((parseFloat(weightCalPf * pfjzPrice) + parseFloat($('#warehouseSurchargePf').val())),2));
			$('#actualLogisticsFreightPf').val(parseFloat($('#priceTranCalWeightPredictPf').val())+parseFloat($('#priceQualityExtraPredictPf').val())
					+parseFloat($('#priceProNameExtraPredictPf').val())+parseFloat($('#priceClearanceOpePf').val()));
		}else {
			$('#priceClearanceOpePf').val(0);
			$('#priceProNameExtraPredictPf').val(0);
			$('#priceQualityExtraPredictPf').val(0);
			$('#priceTranCalWeightPredictPf').val(0);
			$('#actualLogisticsFreightPf').val(0);
		}
	}

	//实际计重=MAX（实重,抛重,单箱起重）实际计重=MAX（A1，单票起重）
	function calculateWeightCal(weightCal,type) {
		for (let i = 0; i <= tablecolsNum; i++) {
			let numRe = 'numRealityDeliver' + i
			if (boxWeight[numRe] != undefined && boxWeight[numRe] != '') {
				if (type == 1) {
					weightCal = weightCal + parseFloat(precision(Math.max(weightCalBySingle, tossWeight[numRe], (boxWeight[numRe]))))
				} else if (type == 2) {
					weightCal = weightCal + Math.max(weightCalBySingle, tossWeight[numRe], (boxWeight[numRe]))
				}
			}
		}
		if (type == 1) {
			a1 = weightCal;
			//A1
			$('#weightCalA1').val(a1);
			if ($('#stateShareTicketName').val() == '否') {
				weightCal = Math.max(singlePassCrane, weightCal);
			}
		}
		return weightCal;
	}

	function isSinglePassCrane(data) {
		if ($('#stateShareTicketName').val() == '否'){
			//A1 < 单票起重，保存提示“头程未满足该渠道的单票发货起重，是否按照该渠道的发货起重去结算发货？”
			if (Number(a1) < Number($('#singlePassCrane').val())){
				$.modal.confirmCom('头程未满足该渠道的单票发货起重，是否按照该渠道的发货起重去结算发货？', function (result) {
					if (result == true){
						postUrl(data)
					}
				})
			}  else {
				postUrl(data)
			}
		} else {
			postUrl(data)
		}
	}

	//post请求
	function  postUrl(data) {
		calculateBoxDataNew();
		$.modal.loading("正在处理中，请稍后...");
		listData1.map((v,i)=>{
			v.iid=i+1
		})
		$.post("/logstics/fbabox/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),sonData:JSON.stringify(listData1)},function(res){
			$.modal.closeLoading()
			layer.msg(res.msg);
			if(res.code==0){
				setTimeout(function(){
					window.location.href = '/logstics/fbabox/edit?guid=' + res.data;
				}, 1000);
			}
		});
	}
</script>

</body>
</html>